package com.fzy.common.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class WebRefererFilter implements Filter {

    protected FilterConfig filterConfig;

    @Override
    public void destroy() {
    }


    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        String redirect = request.getParameter("redirect");
        if (null != redirect && !"".equals(redirect)) {
            if (redirect.endsWith("#")) {
                redirect = redirect.substring(0, redirect.length() - 1);
            }
            request.getSession().setAttribute("referer", redirect);
        } else {
            String referer = request.getHeader("referer");
            if (null != referer && !"".equals(referer) && !"null".equals(referer)) {
                if (referer.endsWith("#")) {
                    referer = referer.substring(0, referer.length() - 1);
                }
                String keywords = filterConfig.getInitParameter("keywords");
                boolean flag = true;
                for (String keyword : keywords.split(",")) {
                    if (referer.contains(keyword)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    request.getSession().setAttribute("referer", referer);
                }
            }
        }
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        this.filterConfig = arg0;
    }

}
